<template>
  <view class="app">
    <view class="main-box">
      <view class="form-box">
        <view class="form-item">
          <text class="item-title">账号密码</text>
          <input type="password" v-model="form.password" placeholder="请输入账号密码" />
        </view>
      </view>
      <view class="form-box">
        <view class="form-item">
          <text class="item-title">手机号码</text>
          <input type="number" maxlength="11" v-model.trim="form.phone" placeholder="请输入新的手机号码" />
        </view>
        <view class="form-item">
          <text class="item-title">验证码</text>
          <view class="flex flex-1 overflow-hidden" @click="openKeyborad()">
            <u-message-input
              mode="bottomLine"
              v-model="form.code"
              width="34"
              font-size="28"
              :maxlength="codeMaxlength"
              :breathe="false"
              :disabled-keyboard="true"
            ></u-message-input>
          </view>
          <u-keyboard
            mode="number"
            v-model="showKeyboard"
            :tooltip="false"
            :dot-enabled="false"
            @change="keyboardChange"
            @backspace="keyboardDelete"
          >
            <view class="paste-btn" @click="pasteCode()">粘贴</view>
          </u-keyboard>
          <view class="smscode-btn" :class="{ 'count-down': countActive }" @click="sendVerifyCode()">
            {{ showCodeText }}
          </view>
        </view>
      </view>
    </view>

    <view class="footer">
      <view class="submit-btn" @click="save()">
        <text class="ml-10rpx">提 交</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { msg } from '@/utils/msg';
  import { changePhone } from '@/api/fans';
  import { sendSmsCaptcha } from '@/api/auth';
  import { useFansStore } from '@/store/fans';
  import { report } from '@/utils/exception';
  import { regexpPhone } from '@/utils/regexp';

  const fansStore = useFansStore();
  const showKeyboard = ref<boolean>(false);
  const codeText = '获取验证码';
  const showCodeText = ref<string>(codeText);
  const countActive = ref<boolean>(false);
  const lifeTime = 60;
  let leftTime = lifeTime;
  let codeMaxlength = 6;

  const form = ref({
    password: '',
    phone: '',
    code: '',
  });

  const openKeyborad = () => {
    form.value.code = '';
    showKeyboard.value = true;
  };

  const keyboardChange = (val: string) => {
    if (form.value.code.length >= codeMaxlength) return;
    form.value.code += val;
    if (form.value.code.length == codeMaxlength) {
      showKeyboard.value = false;
      save();
    }
  };

  const keyboardDelete = () => {
    if (!form.value.code.length) return;
    form.value.code = form.value.code.substring(0, form.value.code.length - 1);
  };

  const pasteCode = () => {
    uni.getClipboardData({
      success: (res) => {
        if (!/^\d{6}$/.test(res.data)) return;
        form.value.code = res.data;
        showKeyboard.value = false;
        save();
      },
    });
  };

  const verifyPhone = () => {
    if (!form.value.phone) {
      msg.error('请输入手机号码');
      return false;
    }
    if (!regexpPhone(form.value.phone)) {
      msg.error('手机号码格式错误');
      return false;
    }
    return true;
  };

  // 发送短信验证码
  const sendVerifyCode = () => {
    if (countActive.value) {
      return;
    }

    if (!verifyPhone()) {
      return;
    }

    // 后台发送验证码
    msg.loading('发送中');
    sendSmsCaptcha(form.value.phone, 'change_phone')
      .then((res) => {
        setTimeout(() => {
          msg.success('验证码已发送');
          countActive.value = true;
          showCodeText.value = leftTime + 's';
          openKeyborad();

          let timer = setInterval(() => {
            if (leftTime == 0) {
              leftTime = lifeTime;
              showCodeText.value = codeText;
              countActive.value = false;
              clearInterval(timer);
              return;
            }

            leftTime--;
            showCodeText.value = leftTime + 's';
          }, 1000);
        }, 1000);
      })
      .catch((err) => {
        setTimeout(() => {
          report(err);
        }, 800);
      });
  };

  // 提交
  const save = () => {
    if (!form.value.password) {
      return msg.error('请输入账号密码');
    }
    if (!verifyPhone()) {
      return;
    }
    if (!form.value.code) {
      return msg.error('请输入验证码');
    }

    msg.loading();
    changePhone(form.value)
      .then((res) => {
        fansStore.clearFansInfo();
        msg.success('手机号更换成功，请重新登录！');
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/auth/login?type=password' });
        }, 2000);
      })
      .catch((err) => {
        report(err);
      });
  };
</script>

<style lang="scss" scoped>
  $fontSize: 28rpx;

  .main-box {
    margin: 25rpx;

    .form-box {
      padding: 0 25rpx;
      background: white;
      border-radius: 20rpx;
      margin-bottom: 20rpx;

      .form-item {
        display: flex;
        align-items: center;
        height: 100rpx;
        // padding: 30rpx 0;

        &:not(:last-child) {
          border-bottom: 1rpx solid $borderColor;
        }

        .item-title {
          font-size: $fontSize;
          font-weight: 600;
          width: 140rpx;
          flex: none;
        }

        input {
          font-size: $fontSize;
          margin-right: 10rpx;
          width: 100%;
        }

        .smscode-btn {
          color: #0851dd;
          font-size: 27rpx;
          width: 165rpx;
          text-align: center;
          margin-left: 20rpx;
          padding-left: 25rpx;
          border-left: 1rpx solid black;
        }

        .count-down {
          color: #8d8d8d;
        }
      }
      .paste-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100rpx;
        border-radius: 12rpx;
        padding: 12rpx 15rpx;
        margin: 12rpx 0 12rpx 30rpx;
        background: #f2f2f2;
      }
    }
  }

  .footer {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    height: 110rpx;

    .submit-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 90%;
      font-size: 26rpx;
      font-weight: 600;
      color: white;
      margin: 0 auto;
      padding: 24rpx 0;
      border-radius: 50rpx;
      letter-spacing: 1rpx;
      background: linear-gradient(315deg, #429ff6, #394eea, #2664ef);
      box-shadow: rgba(29, 154, 244, 0.2) 0 5rpx 12rpx;
    }
  }
</style>
